package com.infomanage.service.syscfg;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspWriter;


import com.base.organization.Organization;
import com.base.organization.OrganizationDAO;
import com.infomanage.util.Consts;
import com.infomanage.util.StringUtil;
import com.infomanage.util.TimeUtil;
import com.jiuqi.util.ReturnObject;
import com.jiuqi.util.StringUtils;

import com.infomanage.authority.AuthorityBean;
import com.infomanage.bean.FieldBean;
import com.infomanage.bean.PaginationBean;
import com.infomanage.bean.SearchBean;
import com.infomanage.dao.DeptDAO;
import com.infomanage.dao.MessageDAO;
import com.infomanage.dao.PersonDAO;
import com.infomanage.enums.RoleType;


import com.infomanage.po.Department;
import com.infomanage.po.Message;
import com.infomanage.po.User;
public class DepartService {
	
	
	public static Department loadDeptById(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String itemId= request.getParameter("itemId");
			if(StringUtils.isEmpty(itemId)) return null;
			DeptDAO dao = new DeptDAO();
			return dao.findById(Integer.parseInt(itemId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<Department> loadDeptByParentId(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		try {
			request.setCharacterEncoding("UTF-8");
			String itemId= request.getParameter("itemId");
			if(StringUtils.isEmpty(itemId)) return null;
			DeptDAO dao = new DeptDAO();
			return dao.findChildren(Integer.parseInt(itemId));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static ReturnObject removeDept(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String dept_id = request.getParameter("itemId");
			
			//此处需要查询人员表
			DeptDAO dao = new DeptDAO();
			List xd_list=dao.findChildren(Integer.parseInt(dept_id));
			List depts=new ArrayList();
			PersonDAO personDao=new PersonDAO();
			for(int i=0;i<xd_list.size();i++){
				Department department=(Department)xd_list.get(i);
				depts.add(department.getDeptId());
			}
			depts.add(Integer.parseInt(dept_id));
			for(int j=0;j<depts.size();j++){
				List personList=personDao.findByDept((Integer)depts.get(j));
				if(personList.size()!=0){
					 ret.SetErrored(true);
					 ret.setErrorMessage("该单位下还有员工，请将员工删除后再删除单位!");
					 return ret;
				}
				
			}
			
			//List personList=personDao.findAll();
			
//			for(int j=0;j<personList.size();j++){
//			   Person person=(Person)personList.get(j);	
//			   int person_deptid=person.getDeptId();
//			   for(int k=0;k<depts.size();k++){
//				   if(person_deptid==(Integer)depts.get(k)){
//					   ret.setErrorMessage("该单位下还有员工，请将员工删除后再删除单位");
//					   return ret;
//				   }
//			   }
//			   
//			}
			for(int k=0;k<depts.size();k++){
				dao.remove(Department.class, (Integer)depts.get(k));
			}
			
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	public static ReturnObject saveDepartment(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			DeptDAO dao = new DeptDAO();
			int parentId = (Integer.parseInt(request.getParameter("parent")));
			Department parentDept = dao.findById(parentId);
			int level = 1;
			if(parentDept != null) {
				level = parentDept.getLevel() + 1;
			}
			Department bean = new Department();
			bean.setName(request.getParameter("name"));
			bean.setParent(parentId);
			bean.setAdress(request.getParameter("adress"));
			bean.setDescription(request.getParameter("description"));
			bean.setLatlng(request.getParameter("latlng"));
			bean.setLevel(level);
			bean.setPath(request.getParameter("path"));
			bean.setTelephoneNo(request.getParameter("telephoneNo"));
			dao.add(bean);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	
	public static ReturnObject modifyDepartment(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			int itemId = Integer.parseInt(request.getParameter("itemId"));
			DeptDAO dao = new DeptDAO();
			Department bean = dao.findById(itemId);
			bean.setName(request.getParameter("name"));
			bean.setAdress(request.getParameter("adress"));
			bean.setLatlng(request.getParameter("latlng"));
			bean.setPath(request.getParameter("path"));
			bean.setTelephoneNo(request.getParameter("telephoneNo"));
			dao.modify(bean);
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(StringUtil.filterIllegalchar(e.getMessage()));
		}
		return ret;
	}
	
	public static ReturnObject removeDepartment(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String itemId = request.getParameter("itemId");
			DeptDAO dao = new DeptDAO();
			List<Department> list = dao.findChildren(Integer.parseInt(itemId));
			if(list != null && list.size() > 0) {
				ret.SetErrored(true);
				ret.setErrorMessage("该单位存在下级单位，不能删除！");
				return ret;
			}
			
			dao.remove(Department.class, Integer.parseInt(itemId));
		} catch (Exception e) {
			ret.SetErrored(true);
			ret.setErrorMessage(e.getMessage());
		}
		return ret;
	}
	
	public static ReturnObject removeBatchDepartment(HttpServletRequest request, HttpServletResponse response, JspWriter out){
		ReturnObject ret = new ReturnObject();
		try {
			request.setCharacterEncoding("UTF-8");
			String batchIds = request.getParameter("batchIds");
			DeptDAO dao = new DeptDAO();
			if(batchIds != null){
				String[] ids = batchIds.split(";");
				for(String id : ids){
					dao.remove(Department.class, Integer.parseInt(id));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			ret.SetErrored(true);
			ret.setErrorMessage("删除失败！");
		}
		return ret;
	}
	
	public static List<Message> search(HttpServletRequest request, HttpServletResponse response, JspWriter out) {
		try {
			request.setCharacterEncoding("UTF-8");
			MessageDAO dao = new MessageDAO();
			SearchBean searchBean = buildSearchCondition(request, response, out);
			// 设置分页
			String currPageNum = request.getParameter("currPageNum");
			PaginationBean page = new PaginationBean();
			if (currPageNum == null) {
				page.setCurrentPageNum(1);
			} else {
				page.setCurrentPageNum(Integer.parseInt(currPageNum));

			}
			searchBean.setPage(page);
			List<Message> list = dao.findByFields(searchBean);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	private static SearchBean buildSearchCondition(HttpServletRequest request, HttpServletResponse response,
			JspWriter out) throws Exception {
		request.setCharacterEncoding("UTF-8");
		String deptName = request.getParameter("deptName");
		String personName = request.getParameter("personName");
		SearchBean searchBean = new SearchBean();
		if (!StringUtil.isEmpty(deptName)) {
			FieldBean field = new FieldBean("deptName", deptName);
			field.setLike(true);
			searchBean.add(field);
		}
		if (!StringUtil.isEmpty(personName)) {
			FieldBean field = new FieldBean("personName", personName);
			field.setLike(true);
			searchBean.add(field);
		}

		// 设置权限
		User user = (User) request.getSession().getAttribute(Consts.LOGINED_USER);
		if (user != null) {
			AuthorityBean authority = new AuthorityBean();
			authority.setRole(RoleType.valueOf(user.getRoleId()));
			authority.setDeptId(user.getAssociatedDept());
			searchBean.setAuthority(authority);
		}
		return searchBean;
	}
}
